package com.robot.mvvm.vm.work

import android.app.Application
import android.text.TextUtils
import androidx.databinding.ObservableField
import api.CommonServiceFactory
import api.UserServiceFactory
import com.blankj.utilcode.util.LogUtils
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.AppConstants
import com.robot.base.model.DicinfoDataDTOBean
import com.robot.base.model.UploadFileBean
import com.robot.base.util.LiveDataBus
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.net.URLEncoder

class AddSafetyViewModel(application: Application) : GLBaseViewModel(application) {

    val photo = ObservableField<String>()
    var photoId = ""
    val personName = ObservableField<String>()
    val sex = ObservableField<String>()
    val age = ObservableField<String>()
    val idCard = ObservableField<String>()
    val contactPhone = ObservableField<String>()
    val education = ObservableField<String>()
    var educationCode = ""
    val major = ObservableField<String>()
    val email = ObservableField<String>()
    val address = ObservableField<String>()
    val certType = ObservableField<String>()
    var certTypeCode = ""
    val gmtCertExpire = ObservableField<String>()
    val certImage = ObservableField<String>()
    var certImageId = ""

    val educationsDicinfoDataDTOBean = arrayListOf<DicinfoDataDTOBean>()
    val professionalCertTypesDicinfoDataDTOBean = arrayListOf<DicinfoDataDTOBean>()

    val uc = UiChangeEvent()

    class UiChangeEvent {
        val showPhotoEvent = SingleLiveEvent<Int>()
        val showDialogEvent = SingleLiveEvent<Int>()
    }

    val confirmCommand = BindingCommand<Any>(BindingAction {
        addSafetyPerson()
    })
    val showPhotoCommand = BindingCommand<Any>(BindingAction {
        uc.showPhotoEvent.postValue(0)
    })

    val showCertImageCommand = BindingCommand<Any>(BindingAction {
        uc.showPhotoEvent.postValue(1)
    })

    val showSexCommand = BindingCommand<Any>(BindingAction {
        uc.showDialogEvent.postValue(0)
    })

    //学历
    val showEducationCommand = BindingCommand<Any>(BindingAction {
        uc.showDialogEvent.postValue(1)
    })

    //证书类型
    val showCertTypeCommand = BindingCommand<Any>(BindingAction {
        uc.showDialogEvent.postValue(2)
    })

    //证件有效截止期
    val showGmtCertExpireCommand = BindingCommand<Any>(BindingAction {
        uc.showDialogEvent.postValue(3)
    })


    //证件类型
    fun professionalCertTypes() {
        CommonServiceFactory.selectDicinfoListByCode(
            mapOf(
                "parent_code" to "ProfessionalCertTypes"
            )
        ).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<List<DicinfoDataDTOBean>>>(this) {
            override fun onNext(t: BaseResponse<List<DicinfoDataDTOBean>>) {
                professionalCertTypesDicinfoDataDTOBean.clear()
                professionalCertTypesDicinfoDataDTOBean.addAll(t.data)
            }
        })
    }

    //证件类型
    fun educations() {
        CommonServiceFactory.selectDicinfoListByCode(
            mapOf(
                "parent_code" to "Educations"
            )
        ).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<List<DicinfoDataDTOBean>>>(this) {
            override fun onNext(t: BaseResponse<List<DicinfoDataDTOBean>>) {
                educationsDicinfoDataDTOBean.clear()
                educationsDicinfoDataDTOBean.addAll(t.data)
            }
        })
    }

    fun upload(
        filePath: String, type: Int,
        result: (fileUrl: String?) -> Unit
    ) {
        if (TextUtils.isEmpty(filePath)) return
        val file = File(filePath)
        val requestFile =
            file.asRequestBody("application/octet-stream".toMediaTypeOrNull())
        val part = MultipartBody.Part.createFormData(
            "file",
            URLEncoder.encode(file.name, "UTF-8"),
            requestFile
        )
        CommonServiceFactory.uploadFile(
            part, mapOf(
                "serviceType" to if (type == 0) {
                    "photo"
                } else {
                    "cert_img"
                }
            )
        ).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<UploadFileBean>>(this) {
            override fun onNext(t: BaseResponse<UploadFileBean>) {
                if (t.data != null && !TextUtils.isEmpty(t.data.fileUrl)) {
                    when (type) {
                        0 -> {
                            photoId = t.data.fileId ?: ""
                            photo.set(t.data.fileUrl)
                        }

                        1 -> {
                            certImageId = t.data.fileId ?: ""
                            certImage.set(t.data.fileUrl)
                        }
                    }

                    result.invoke(t.data.fileUrl)
                }
            }

            override fun onError(e: Throwable) {
                super.onError(e)
                LogUtils.i(e)
                result.invoke(null)
            }
        })
    }

    fun addSafetyPerson() {
        showLoadingDialog()
        UserServiceFactory.addSafetyPerson(
            mapOf(
                "address" to (address.get() ?: ""),
                "age" to (age.get() ?: ""),
                "certImageId" to certImageId,
                "certTypeCode" to certTypeCode,
                "contactPhone" to (contactPhone.get() ?: ""),
                "educationCode" to educationCode,
                "email" to (email.get() ?: ""),
                "gmtCertExpire" to (gmtCertExpire.get() ?: ""),
                "idCard" to (idCard.get() ?: ""),
                "major" to (major.get() ?: ""),
                "personName" to (personName.get() ?: ""),
                "photoId" to photoId,
                "sex" to when (sex.get()) {
                    "男" -> {
                        "1"
                    }
                    "女" -> {
                        "0"
                    }
                    else -> {
                        ""
                    }
                }
            )
        ).subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
            override fun onNext(t: BaseResponse<String>) {
                LiveDataBus.get().with(AppConstants.LiveKey.SAFETY_REFRESH_DATA).postValue("")
                finish()
            }
        })
    }
}